'use strict';

const Service = require('egg').Service;
const svgCaptcha = require('svg-captcha');

class UserService extends Service {
  /**
   * 获取用户数据
   * @param {*} userData 用户数据
   */
  _userData(userData) {
    if (!userData) { return null; }
    return {
      user: userData.user,
      icon: userData.icon,
      type: userData.type,
      createTime: userData.createTime,
      role: userData.role,
    };
  }

  /**
   * 获取验证码 Verification code
   */
  verificationCode() {
    const codeModel = svgCaptcha.create();
    this.ctx.session.verificationCode = codeModel.text.toLocaleLowerCase();
    this.ctx.response.type = 'image/svg+xml';
    this.ctx.body = codeModel.data;
  }

  /**
   * 登录
   * @param {*} param 登录参数
   */
  async login({ user, pass, code }) {
    const { User } = this.ctx.model;
    if (this.ctx.session.verificationCode !== code.toLocaleLowerCase()) {
      throw new Error('验证码错误');
    }
    // 查找账号
    const userData = await User.findWithUser(user);
    // 如果没有找到用户直接抛出错误
    if (!userData) {
      throw new Error('当前用户未注册');
    }
    // 判断用户登录错误次数
    if (userData.loginErrNum > 3) {
      throw new Error('登录错误次数超过3次');
    }
    const passMD5 = this.ctx.w_tool.MD5(pass);
    // 判断账号密码是否正确
    if (passMD5 !== userData.pass) {
      // 记录登录错误加1
      await userData.addLoginErrNum();
      throw new Error('密码错误');
    }
    // 清除登录错误
    userData.clearLoginErrNum();
    // ==== 用户通过验证 session记录数据 =====
    this.ctx.session.userModel = userData;
    // 清除验证码
    this.ctx.session.verificationCode = null;
    // 返回的数据
    const resData = this._userData(userData);
    return resData;
  }

  /**
   * session登录
   */
  async sessionLogin() {
    const { userModel } = this.ctx.session;
    const userData = this._userData(userModel);
    return userData;
  }

  /**
   * 更新数据
   */
  async update() {
    const id = this.ctx.params.id;
    const data = this.ctx.w_body();
    const { User } = this.ctx.model;
    if (data.pass) {
      data.pass = this.ctx.w_tool.MD5(data.pass);
    }
    if (id) {
      return await User.updateUser(id, data);
    }
    return await User.updateCurrentUser(this.ctx.session.userModel.user, data);
  }

  /**
   * 创建用户
   */
  async create() {
    const { User } = this.ctx.model;
    const { pass, role, user } = this.ctx.w_body();
    return await new User({
      role,
      user,
      pass: this.ctx.w_tool.MD5(pass),
    }).save();
  }

  /**
	 * 获取所有用户
	 */
  async all() {
    return await this.ctx.model.User.findAll();
  }

  /**
	 * 删除用户
	 */
  async destroy() {
    const id = this.ctx.params.id;
    return await this.ctx.model.User.removeUser(id);
  }

  async say() {
    return 'Hello Man!';
  }
}

module.exports = UserService;
